package com.ali.common;

import org.apache.tomcat.util.codec.binary.Base64;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

public class HttpFileUtil {
    /**
     * 使用Http的Get请求下载文件
     */
    public static void downloadFileHttpGet(String fileUrl, String savePath, String fileName) {
        Map<String, Object> responseMap = URLConnectionUtil.httpGet(fileUrl, null, true);
        String response = (String) responseMap.get("response");
        byte[] responseByte = Base64.decodeBase64(response);
        writeFile(responseByte, savePath, fileName);
    }

    /**
     * 使用Https的Get请求下载文件
     */
    public static void downloadFileHttpsGet(String fileUrl, String savePath, String fileName) {
        Map<String, Object> responseMap = URLConnectionUtil.httpsGet(fileUrl, null, true);
        String response = (String) responseMap.get("response");
        byte[] responseByte = Base64.decodeBase64(response);
        writeFile(responseByte, savePath, fileName);
    }

    /**
     * 写入文件
     */
    private static void writeFile(byte[] fileData, String savePath, String fileName) {
        File file = new File(savePath + File.separator + fileName);
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            fileOutputStream.write(fileData);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }
}